#include "Mini58Series.h"
#include "app.h"
#include "app_work.h"
#include "app_uart.h"
#include "app_flash.h"
#include "bsp.h"
#include "bsp_timer0.h"
#include "bsp_uart_fifo.h"
#include "lite-log.h"
#include "utils_timer.h"
#include "wdt.h"

#define PLL_CLOCK 50000000

void SYS_Init(void) {
  /* Unlock protected registers */
  SYS_UnlockReg();

  /* Enable  HIRC */
  //	CLK->PWRCTL |= CLK_PWRCTL_HIRCEN_Msk;
  /* Enable HIRC clock (Internal RC 22.1184MHz) */
  CLK_EnableXtalRC(CLK_PWRCTL_HIRCEN_Msk);

  /* Wait for HIRC clock ready */
  CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk);

  /* Select HCLK clock source as HIRC and and HCLK source divider as 1 */
  CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC, CLK_CLKDIV_HCLK(1));

  /* Set core clock as PLL_CLOCK from PLL */
  CLK_SetCoreClock(PLL_CLOCK);
  /* To update the variable SystemCoreClock */
  SystemCoreClockUpdate();

  /* Set P3 multi function pin for Timer 0 capture pin */
  // SYS->P3_MFP = SYS_MFP_P36_TM1_EXT;

  /* Lock protected registers */
  SYS_LockReg();
}

// static iotx_time_t g24_loop_timer;

/*---------------------------------------------------------------------------------------------------------*/
/* MAIN function */
/*---------------------------------------------------------------------------------------------------------*/
int main(void) {
  //  uint8_t ucKeyCode;
  uint8_t blink_cnt = 0;

  /* Init System */
  SYS_Init();

  bsp_Init();

  app_work_init();
	app_flash_init();

  printf(" CPU @ %uHz", SystemCoreClock);

  while (1) {
		
		if (timer0_taskTimer_get()->flag_10ms) {
      timer0_taskTimer_get()->flag_10ms = 0;
			app_uart_loop();
		}		
    if (timer0_taskTimer_get()->flag_100ms) {
      timer0_taskTimer_get()->flag_100ms = 0;
     // SYS_UnlockReg();
      // WDT_RESET_COUNTER();
     // SYS_LockReg();
       app_work_loop();
      //bsp_uart_send_byte(1, 0xA5);
    }
		if (timer0_taskTimer_get()->flag_1s) {
      timer0_taskTimer_get()->flag_1s = 0;
		//	bsp_uart_send_byte(0, 0xA5);
		}
		
  }
}
